﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;

namespace Mind.Data
{
    public class DataReaderIterator<T> : IDisposable
    where T : IDataReadable, new()
    {
        private DbDataReader _Reader;

        public DbDataReader Reader
        {
            get { return _Reader; }
        }

        public DataReaderIterator(DbDataReader reader)
        {
            _Reader = reader;
        }

        public List<T> ToList()
        {
            List<T> result = new List<T>();
            IEnumerator<T> enumerator = this.GetEnumerator();
            while (enumerator.MoveNext())
            {
                result.Add(enumerator.Current);
            }

            Dispose();
            return result;
        }

        public IEnumerator<T> GetEnumerator()
        {
            while (_Reader.Read())
            {
                T result = new T();
                if (!result.LoadFromDataReader(_Reader))
                    break;
                yield return result;
            }

        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!_Reader.IsClosed)
                _Reader.Close();
            _Reader.Dispose();
        }

        #endregion
    }
}